package com.silverhaze.diamond.client.utils;

import com.silverhaze.commons.ui.dialogs.ErrorDialog;
import com.silverhaze.commons.utils.StringUtils;
import com.silverhaze.diamond.client.ui.UIHelper;

import javax.swing.*;

/**
 * Created by IntelliJ IDEA.
 * SystemUser: Ivan
 * Date: 30.06.2008
 * Time: 22:17:19
 * To change this template use File | Settings | File Templates.
 */
public class ServiceExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static final String ERROR_HAPPENS = "Произошел сбой программы. ";
    private static final String ERROR_TEXT = "Текст ошибки";
    private static final String STACK_TRACE = "Трейс стека:";
    private static final String REPEATED_ERROR_MESSAGE = "Система не смогла справиться с ошибкой: %s, порожденной ошибкой: %s";

    private void handleException(final Throwable e) {
        try {
            final String message = ERROR_HAPPENS
                    + (e.getMessage() != null ? "\n" + ERROR_TEXT + ": " + e.getMessage() : "");
            final String details = STACK_TRACE + ": " + StringUtils.getStackTrace(e);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        ErrorDialog errorDialog = new ErrorDialog(UIHelper.getMainFrame(), message, details, e.getMessage());
                        errorDialog.setVisible(true);
                    } catch (Throwable t) {
                        handleRepeatedException(t, e);
                    }
                }
            });
        } catch (Throwable t) {
            handleRepeatedException(t, e);
        }

        e.printStackTrace();
    }

    private void handleRepeatedException(Throwable t, Throwable e) {
        t.printStackTrace();
        System.err.println(String.format(REPEATED_ERROR_MESSAGE, String.valueOf(e), String.valueOf(t)));
    }

    public void uncaughtException(Thread t, Throwable e) {
        handleException(e);
    }
}
